package com.example.rabbitdemo.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 周宇
 * @version 1.0 date: 2019/7/22 17:21
 * @description: rabbit设置
 * @Copyright (C), 2017-2019, 深圳市⾦证引擎科技股份有限公司
 */
@Configuration
@Log4j2
public class RabbitConfig {

  @Autowired
  RabbitProperties rabbitProperties;

  @Bean("connectionFactory")
  public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    //防止信道缓存不够造成消息丢失，官方推荐100可完全避免此丢失消息情况
    connectionFactory.setChannelCacheSize(100);
    connectionFactory.setAddresses(rabbitProperties.getAddresses());
    connectionFactory.setUsername(rabbitProperties.getUsername());
    connectionFactory.setPassword(rabbitProperties.getPassword());
    connectionFactory.setVirtualHost(rabbitProperties.getVirtualHost());
    //开启确认机制，可监听消息是否到达交换机
    connectionFactory.setPublisherConfirms(rabbitProperties.isPublisherConfirms());
    //成功到达返回true
    connectionFactory.setPublisherReturns(true);
    return connectionFactory;
  }

  @Bean
  public DirectExchange directExchange() {
    DirectExchange directExchange = new DirectExchange("zhouyu_direct");
    return directExchange;
  }

  @Bean
  public Queue directQueue1() {
    Queue queue = new Queue("zhouyu_directqueue1");
    return queue;
  }

  @Bean
  public Binding bindingorange() {
    Binding binding = BindingBuilder.bind(directQueue1()).to(directExchange())
        .with("zhouyu.orange");
    return binding;
  }

}
